﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Ooganizer.Closer;
using Ooganizer.Platform.Win32;

namespace Ooganizer.Closer
{
    public class MSWordCloser : ICloser, ICloseable
    {
        public const string ProgId = "Word.Application";

        public bool CanClose(string processName)
        {       
            switch (processName.ToLower())
            {
                case "winword":
                    return true;
                default:
                    return false;
            }
        }

        public bool CloseApp(IntPtr hWnd, string location)
        {
            bool bClosed = false;

            Microsoft.Office.Interop.Word.Application app = null;
            app = Win32Functions.GetCOMObject(ProgId) as Microsoft.Office.Interop.Word.Application;

            foreach (Microsoft.Office.Interop.Word.Document doc in app.Documents)
            {
                if (doc.FullName.ToLower() == location.ToLower())
                {
                    // Found the document to close
                    object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdPromptToSaveChanges;

                    try
                    {
                        bool bLastDocumentInWord = (app.Documents.Count == 1);

                        Object missing = Missing.Value;
                        doc.Close(ref saveOption, ref missing, ref missing);

                        bClosed = true;

                        if (bLastDocumentInWord)
                            app.Quit(ref saveOption, ref missing, ref missing);
                    }
                    catch (Exception e)
                    {
                        string message = e.Message;
                        message = message + "";
                        // TODO: Log Something here
                    }                    

                    break;
                }
            }

            return bClosed;
        }
    }

}
